import { BadRequestException, Injectable } from '@nestjs/common'
import { UpdateUserDto } from './dto/update-user.dto'
import { PrismaService } from 'src/common/prisma/prisma.service'
import { UpdatePassword } from './dto/update-password.dto'
import * as bcrypt from 'bcryptjs'

@Injectable()
export class UserService {
   constructor(private readonly prisma: PrismaService) {}
   async findOne(id: number) {
      const res = await this.prisma.user.findFirst({
         where: { id }
      })
      res.avatar = res.avatar ? res.avatar : '../../uploads/avt-2.jpeg'
      delete res.password
      return res
   }

   async upUserInfo(updateUserDto: UpdateUserDto, id: number) {
      try {
         await this.prisma.user.update({
            where: {
               id
            },
            data: {
               ...updateUserDto
            }
         })
         return { message: '更新成功' }
      } catch (error) {
         throw new BadRequestException({ message: error })
      }
   }

   async upPassword(updatePassword: UpdatePassword, userId: number) {
      const res = await this.prisma.user.findFirst({
         where: {
            id: userId
         }
      })

      const check = bcrypt.compareSync(updatePassword.oldPassword, res.password)

      if (!check) throw new BadRequestException('旧密码有误')
      await this.prisma.user.update({
         where: {
            id: +userId
         },
         data: {
            password: bcrypt.hashSync(updatePassword.newPassword, 10)
         }
      })

      return { message: '更新成功' }
   }

   async findUserCommontList(userId: number) {
      return await this.prisma.commont.findMany({
         where: { userId },
         include: {
            articel: true
         }
      })
   }

   // 添加经纬度
   async upLocation(userId: number, updateLocation: { latitude: number; longitude: number }) {
      const user = await this.prisma.user.update({
         where: {
            id: userId
         },
         data: {
            latitude: updateLocation.latitude,
            longitude: updateLocation.longitude
         }
      })
      return user
   }
}
